package datacache

import (
	"encoding/binary"
	"fmt"
	"math"
	"time"

	"gitee.com/haodreams/libs/ee"
)

// DeadbandConst 死区的最小常量
const DeadbandConst = 0.000001

// FloatEqual 判断是否相等
func FloatEqual(a, b float64) bool {
	return math.Abs(a-b) < 0.0001
}

// Deadband 死区判断，判断是否在死区范围内
func Deadband(a, b, c float64) bool {
	return math.Abs(a-b) < c
}

// Item 数据
type Item struct {
	ID         int32
	Value      float64
	Status     byte
	Time       int32
	Deadband   float64
	LastValue  float64
	LastStatus byte
}

// String 字符串
func (me *Item) String() string {
	return fmt.Sprintf("%d,%.5f,%d,%s", me.ID, me.Value, me.Status, time.Unix(int64(me.Time), 0).Format("2006-01-02 15:04:05"))
}

// Encode 编码
func (me *Item) Encode() []byte {
	data := make([]byte, 17)
	pos := 0
	binary.BigEndian.PutUint32(data[pos:], uint32(me.ID))
	pos += 4
	binary.BigEndian.PutUint64(data[pos:], math.Float64bits(me.Value))
	pos += 8
	data[pos] = me.Status
	pos++
	binary.BigEndian.PutUint32(data[pos:], uint32(me.Time))
	pos += 4
	return data
}

// Decode 解码
func (me *Item) Decode(b []byte) (err *ee.Error) {
	if len(b) < 17 {
		return ee.NewError("Decode error, Length too short")
	}
	pos := 0
	me.ID = int32(binary.BigEndian.Uint32(b[pos:]))
	pos += 4
	me.Value = math.Float64frombits(binary.BigEndian.Uint64(b[pos:]))
	pos += 8
	me.Status = b[pos]
	pos++
	me.Time = int32(binary.BigEndian.Uint32(b[pos:]))
	return
}
